package ticket;

/**
 * @Author Stringzhua
 * @Date 2024/10/29 14:34
 * description:
 */
public class Test02 {
    public static void main(String[] args) {
        final Object lock = new Object();
        TicketPoolX ticketPool = new TicketPoolX(30, lock);

        new Thread(ticketPool, "窗口1").start();
        new Thread(ticketPool, "窗口2").start();
        new Thread(ticketPool, "窗口3").start();
    }
}

class TicketPoolX implements Runnable {
    //当前剩余门票数
    private int ticket;
    //锁对象
    private Object lock;

    public TicketPoolX(int ticket, Object lock) {
        this.ticket = ticket;
        this.lock = lock;
    }

    public int getTicket() {
        return ticket;
    }

    public void setTicket(int ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始卖票");
        //不同的售票窗口[线程],使用相同的当前对象(公共票池)
        synchronized (lock) {
            while (true) {
                if (ticket <= 0) {
                    System.out.println(Thread.currentThread().getName() + "没票啦");
                    return;
                } else {
                    System.out.println(Thread.currentThread().getName() + "卖出了一张票,剩余:" + --ticket + "张门票");
                    try {
                        //sleep()执行期间(休眠期间),持有当前锁的线程,不会释放锁[单个窗口卖30张票]
//                        Thread.sleep(1000);

//                        wait()执行期间(等待期间),持有当前锁的线程,会释放锁[多个窗口卖30张票]
                        lock.wait(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
